<template>
  <el-form
    inline
    :model="searchForm"
    class="common-search"
  >
    <template
      v-for="(item, index) in items"
      :key="index"
    >
      <el-form-item :label="item.label">
        <el-input
          v-if="item.type === 'input'"
          v-model="searchForm[item.prop]"
          :placeholder="item.placeholder || `请输入${item.label}`"
          :clearable="item.clearable ?? true"
          v-bind="item.props"
        />

        <el-select
          v-else-if="item.type === 'select'"
          v-model="searchForm[item.prop]"
          :placeholder="item.placeholder || `请选择${item.label}`"
          :clearable="item.clearable ?? true"
          v-bind="item.props"
        >
          <el-option
            v-for="opt in item.options || []"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>
    </template>

    <!-- 操作按钮 -->
    <el-form-item>
      <el-button
        type="primary"
        @click="handleSearch"
        >搜索</el-button
      >
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  // 搜索项配置类型
  export interface SearchItem {
    prop: string
    label: string
    type: 'input' | 'select'
    placeholder?: string
    clearable?: boolean
    options?: { label: string; value: any }[]
    props?: Record<string, any>
  }

  const props = defineProps<{
    // 搜索项配置
    items: SearchItem[]
    // 初始搜索值
    initialValues?: Record<string, any>
  }>()

  const emit = defineEmits<{
    (e: 'search', values: Record<string, any>): void
    (e: 'reset'): void
  }>()

  // 搜索表单数据
  const searchForm = reactive<Record<string, any>>({
    ...props.initialValues,
  })

  // 初始化默认值
  props.items.forEach(item => {
    if (!Object.prototype.hasOwnProperty.call(searchForm, item.prop)) {
      searchForm[item.prop] = ''
    }
  })

  // 搜索
  const handleSearch = () => {
    emit('search', { ...searchForm })
  }

  // 重置
  const handleReset = () => {
    props.items.forEach(item => {
      searchForm[item.prop] = ''
    })
    emit('reset')
  }

  // 暴露方法
  defineExpose({
    getValues: () => ({ ...searchForm }),
    setValues: (values: Record<string, any>) => Object.assign(searchForm, values),
  })
</script>

<style scoped>
  .common-search {
    padding: 16px;
    background: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 16px;
  }

  .el-form-item {
    margin-right: 16px;
    margin-bottom: 16px;
  }
</style>
